from django.http import HttpResponse
from django.shortcuts import render
from .models import User
from .serializers import UserSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Create your views here.


class RegisterApiView(APIView):
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"code": 200, "message": "User registered successfully"})
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


def add_user(request):
    user = User(username='test', password='test')
    user.save()  # 保存到数据库
    return HttpResponse(user.id)


def get_user(request):
    users = User.objects.all()  # get all users
    for user in users:
        print(user)
    user = User.objects.get(id=1)
    print(user.username)
    user = User.objects.filter(username='test')
    print(user)
    user = User.objects.get(id=1)
    user.username = 'new_name'  # 修改属性
    user.save()  # 更新到数据库
    return HttpResponse('User retrieved successfully')


def user_sort(request):
    users = User.objects.order_by('time')  # sort by time
    # users = User.objects.order_by('-time')  # 反向排序
    for user in users:
        print(user.time)
    return HttpResponse(users)


def user_delete(request, id):
    users = User.objects.get(id=id)
    users.delete()  # 删除用户
    return HttpResponse('User deleted successfully')

